package book.ssl;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

import com.sun.net.ssl.internal.www.protocol.https.Handler;

public class HttpsURLConnectionTest {

	public static void main(String[] args) throws IOException, NoSuchAlgorithmException, KeyStoreException, CertificateException, UnrecoverableKeyException, KeyManagementException {
		
		FileInputStream in = new FileInputStream("/Users/apple/Documents/demo.keystore");
		KeyStore store = KeyStore.getInstance("JKS");
		store.load(in, "123456".toCharArray());
		in.close();
		
		TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("Sunx509");
		trustManagerFactory.init(store);
		
		KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("Sunx509");
		keyManagerFactory.init(store, "123456".toCharArray());
		
		SSLContext context = SSLContext.getInstance("ssl");
		context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
		SSLSocketFactory sslSocketFactory = context.getSocketFactory();
		
		URL url = new URL(null, "https://www.baidu.com/", new Handler());
		HttpsURLConnection con = (HttpsURLConnection)url.getContent();
		con.setDoInput(true);
		con.setDoOutput(true);
		
		con.setSSLSocketFactory(sslSocketFactory);
		InputStream is = con.getInputStream();
		int length = con.getContentLength();
		is.close();
		System.out.println(length);
		
	}
}
